package com.yinhai.activity;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.lz.util.Utils;
import com.yinhai.constant.UrlConstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

/**
 * UpdateActivity （版本更新）
 * 
 * @author Juyon
 */
public class UpdateActivity extends Activity {

	private TextView updateView = null;

	private TextView currVersion = null;

	private static String msg = "您现在使用的最新版本v1.0.0,无需升级";
	private Context context;
	private AQuery aq = null;
	 private ProgressDialog mDialog;
	 private File fileDownloaded;
	 private boolean isDownloading = true;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_update);
		context = this;
		aq = new AQuery(context);
		updateView = (TextView) findViewById(R.id.updateView);
		updateView.setOnClickListener(onClickListener);

		currVersion = (TextView) findViewById(R.id.more_update_currentVersion);

		try {
			PackageInfo info = this.getPackageManager().getPackageInfo(
					this.getPackageName(), 0);
			currVersion.setText("当前版本:v" + info.versionName);
			msg = "您现在使用的最新版本v" + info.versionName + ",无需升级";
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void doBack(View view) {
		onBackPressed();
	}

	private ProgressDialog progressDialog;

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.updateView:
//				progressDialog = ProgressDialog.show(UpdateActivity.this,
//						"版本更新", "正在检查更新...");
//				new MyAsyncQueryHandler().execute(0);
				if(isConnect(context)) {
					checkAppVersion();
				} else {
					Utils.showToast(context, "当前网络不可用!");
				}
				break;

			default:
				break;
			}
		}
	};

	private class MyAsyncQueryHandler extends
			AsyncTask<Integer, Integer, Integer> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Integer doInBackground(Integer... params) {
			switch (params[0]) {
			case 0:
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				break;

			default:
				break;
			}
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			switch (result) {
			case 0:
				progressDialog.dismiss();
				new AlertDialog.Builder(UpdateActivity.this)
						.setTitle("版本更新")
						.setMessage(msg)
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).create().show();
				break;

			default:
				break;
			}
		}
	}
	  public static boolean isConnect(Context context) {
	        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
	        try {
	            ConnectivityManager connectivity =
	                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
	            if (connectivity != null) {
	                // 获取网络连接管理的对象
	                NetworkInfo info = connectivity.getActiveNetworkInfo();
	                if (info != null && info.isConnected()) {
	                    // 判断当前网络是否已经连接
	                    if (info.getState() == NetworkInfo.State.CONNECTED) {
	                        return true;
	                    }
	                }
	            }
	        } catch (Exception e) {
	        }
	        return false;
	    }
	  
	  private void checkAppVersion() {
		  String url = UrlConstant.LOCAL_URI + UrlConstant.VSERSION;
          url = url + "?version=" + UrlConstant.VSERSION_NUM;
          aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
              @Override
              public void callback(String url, JSONObject object, AjaxStatus status) {
                  
                  try {
                      
                      if (object != null) {
                          boolean isFlag = object.getBoolean("success");
                          if (isFlag) {
                              showUpdataDialog();
                          } else {
                             Utils.showToast(context, "当前是最新版本无需更新!");
                              
                          }
                      }
                      
                  } catch (Exception e) {
                  }
                  
              }
          });
	  }
	  
	  public void showUpdataDialog() {
	        AlertDialog.Builder builer = new Builder(this);
	        builer.setTitle("版本升级");
	        builer.setMessage("当前不是最新版本!");
	        // 当点确定按钮时从服务器上下载 新的apk 然后安装
	        builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	                downLoadApk();
	            }
	        });
	        // 当点取消按钮时进行登录
	        builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	                
	            }
	        });
	        AlertDialog dialog = builer.create();
	        dialog.show();
	    }
	  
	  // 下载apk文件
	    protected void downLoadApk() {
	        mDialog = new ProgressDialog(context);
	        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置风格为长进度条
	        mDialog.setTitle("提示");// 设置标题 29
	        mDialog.setMessage("正在下载中，请稍后");
	        mDialog.setIndeterminate(false);// 设置进度条是否为不明确 false 就是不设置为不明确
	        mDialog.setCancelable(false);// 设置进度条是否可以按退回键取消
	        mDialog.setProgress(0);
	        mDialog.incrementProgressBy(1); // 增加和减少进度，这个属性必须的
	        mDialog.setMax(100);
	        mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "取消", new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                dialog.cancel();
	                isDownloading = false;
	            }
	        });
	        mDialog.show();
	        
	        new Thread() {
	            @Override
	            public void run() {
	                try {
	                    fileDownloaded =
	                        getFileFromServer(UrlConstant.LOCAL_URI + "getAndroidApk?apkName=group-android-app", mDialog);
	                    if (mDialog.getProgress() >= 100 || fileDownloaded != null) {
	                        installApk(fileDownloaded);
	                    }
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
	            }
	        }.start();
	        
	    }
	    // 安装apk
	    public void installApk(File file) {
	        mDialog.dismiss();
	        // 执行的数据类型
	        Intent install = new Intent();
	        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        install.setAction(android.content.Intent.ACTION_VIEW);
	        install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
	        context.startActivity(install);
	    }
	    
	    // 从服务器下载apk:
	    public File getFileFromServer(String path, ProgressDialog pd)
	        throws Exception {
	        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
	        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
	            URL url = new URL(path);
	            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	            conn.setConnectTimeout(5000);
	            // 获取到文件的大小
	            pd.setMax(conn.getContentLength());
	            InputStream is = conn.getInputStream();
	            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
	            FileOutputStream fos = new FileOutputStream(file);
	            BufferedInputStream bis = new BufferedInputStream(is);
	            byte[] buffer = new byte[1024];
	            int len;
	            int total = 0;
	            while ((len = bis.read(buffer)) != -1) {
	                if (!isDownloading) {
	                    break;
	                }
	                fos.write(buffer, 0, len);
	                total += len;
	                // 获取当前下载量
	                pd.setProgress(total);
	            }
	            fos.close();
	            bis.close();
	            is.close();
	            return file;
	        } else {
	            return null;
	        }
	    }
}
